<template>
  <div class="cart">
    <!-- 定义插槽以便于父组件分发内容 -->
    <!-- 通过为 slot 绑定 attribute 向父组件分发的内容传递数据 -->
    <slot :items="items"></slot>
  </div>
</template>

<script>
export default {
    name: 'ShoppingCart',
    data(){
      return {
        items: [
            { id: 101 , name: '红米10A' , price: 699 , amount: 1 },
            { id: 202 , name: '魅蓝10' , price: 899 , amount: 1 },
            { id: 303 , name: '荣耀X10' , price: 1899 , amount: 1 }
        ]
      }
    },
    methods: {
      change( { id ,amount } ){
        let item = this.items.find( item => item.id == id );
        if( item ) {
          item.amount = amount ;
        }
      },
      remove( id ) {
        console.log( 'id: ' , id );
        let index = this.items.findIndex( item => item.id == id );
        if( index != -1 ) {
          this.items.splice( index , 1 );
        }
      }
    },
    // 在生命周期钩子中监听事件
    beforeMount(){
      // 监听商品条目数量改变事件
      this.$eventBus.on( this.$amountChange , this.change );
      this.$eventBus.on( this.$removeItem , this.remove );
    }
}
</script>

<style scoped>
.cart {
    margin: 15px auto;
    border: 1px solid blue ;
    width: 80vw;
}
</style>